package com.groupbuying.file.controller;

import com.groupbuying.file.utils.JSONUtils;
import com.groupbuying.file.utils.ParamUtils;
import com.groupbuying.file.utils.ReturnUtils;
import com.groupbuying.file.service.FileService;
import com.groupbuying.file.service.OssCatelogService;
import com.groupbuying.file.service.OssFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *
 * @author wenguoqiang
 * @email 17081@mengtaigroup.com
 * @date 2019-02-19 11:18:09
 */

@RestController
@RequestMapping()
public class FileController {

    private static Logger log = LoggerFactory.getLogger(FileController.class);

    
    @Autowired
    private FileService fileService;

    /**
     * 上传单文件,商户相关接口
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/store/uploadFile")
    @ResponseBody
    public Object storeUploadFile(MultipartFile file, HttpServletRequest request , HttpServletResponse response){
        String responseStr = "";
        Map<String,Object> returnMap = null;
        Map<String,Object> mapParams = ParamUtils.getParamMap(request);
        mapParams.put("files",file);
        mapParams.put("applicationName","store");
        try {
            returnMap = fileService.uploadFile(mapParams);
        }  catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            //responseStr = JsonUtils.objectToJson(returnMap);
        }
        return returnMap;
        //return ReturnUtils.appendResultStr(log,responseStr,"uploadFile");
    }

    /**
     * 上传多文件
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/uploadMoreFiles")
    @ResponseBody
    public Object uploadFile(MultipartFile [] files, HttpServletRequest request , HttpServletResponse response){
        String responseStr = "";
        Map<String,Object> returnMap = null;
        Map<String,Object> mapParams = ParamUtils.getParamMap(request);
        mapParams.put("files",files);
        try {
            returnMap = fileService.uploadMoreFiles(mapParams);
        }  catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.beanToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"uploadMoreFiles");
    }

    /**
     * 多文件临时访问
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = { "/tempVisit" }, produces = { "text/html;charset=UTF-8" }, method = {
            RequestMethod.POST })
    @ResponseBody
    public Object tempVisit ( HttpServletRequest request , HttpServletResponse response){
        String responseStr = "";
        Map<String,Object> returnMap = null;
        Map<String,Object> mapParams = ParamUtils.getParamMap(request);
        try {
            returnMap = fileService.tempVisit(mapParams);
        }  catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.beanToJson(returnMap);
        }
        return ReturnUtils.appendResultStr(log,responseStr,"tempVisit");
    }

    /**
     * 单文件下载
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = { "/singleDownLoadFile" }, produces = { "text/html;charset=UTF-8" })
    @ResponseBody
    public void singleDownLoadFile ( HttpServletRequest request , HttpServletResponse response){
        //http:image/shdus.png
        Map<String,Object> returnMap = null;
        Map<String,Object> mapParams = ParamUtils.getParamMap(request);
        InputStream fis = null;
        try {
            returnMap = fileService.singleDownLoadFile(mapParams);
            fis = (InputStream) returnMap.get("stream");
            response.setHeader("Content-Disposition", "inline;filename="+ returnMap.get("fileName"));
            response.setContentType(returnMap.get("fileType").toString());//也可支持gif
            OutputStream os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("下载文件失败");
        }finally{
            try {
                if(fis!=null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 单文件下载 feign 调用
     * @param fileUuid
     * @return
     */
    @PostMapping("/rpcDownLoadFile")
    public ResponseEntity<Resource> rpcDownLoadFile (@RequestParam("fileUuid")String fileUuid) {
        ResponseEntity<Resource> entity = null;
        try {
            entity = fileService.getFileStream(fileUuid);
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载文件失败:"+e.getMessage());
        }
        return entity;
    }

    /**
     * feign 方式上传
     * @param files
     * @param applicationName
     * @return
     */
    @PostMapping("/rpcUploadFile")
    public Object rpcUploadFile (@RequestPart("files")MultipartFile[] files ,@RequestParam("applicationName") String applicationName) {
        String responseStr = "";
        Map<String,Object> mapParams = new HashMap<>();
        mapParams.put("files",files);
        mapParams.put("applicationName",applicationName);
        Map<String,Object> returnMap = null;
        try {
            returnMap = fileService.uploadMoreFiles(mapParams);

        }  catch (Exception e) {
            returnMap = ReturnUtils.getExceptionResult(log,e);
        } finally {
            responseStr = JSONUtils.beanToJson(returnMap);
        }

        return ReturnUtils.appendResultStr(log,responseStr,"rpcUploadFile");
    }

    /**
     * 获取fileUuid数组
     * @param fileGroupKey
     * @return
     */
    @GetMapping("/getFileUuids")
    public List<String> getFileUuids(@RequestParam("fileGroupKey") String fileGroupKey){
        List<String> fileUuids = null;
        try {
            fileUuids = fileService.getFileUuids(fileGroupKey);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取fileUuids 失败:"+e.getMessage());
        }
        return fileUuids;
    }

    @GetMapping("/getOssFileNames")
    public List<String> getOssFileNames(@RequestParam("fileGroupKey") String fileGroupKey){
        List<String> ossFileNames = null;
        try {
            ossFileNames = fileService.getOssFileNames(fileGroupKey);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取ossFileNames 失败:"+e.getMessage());
        }
        return ossFileNames;
    }

    @GetMapping("/getDownloadUrl")
    public String getDownLoadUrl(@RequestParam("fileUuid") String fileUuid){
        String downLoadUrl = null;
        try {
            downLoadUrl = fileService.getDownLoadUrl(fileUuid);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取下载地址 失败:"+e.getMessage());
        }
        return downLoadUrl;
    }

    @GetMapping("/getDownloadUrlByFileGroupKey")
    public Object getDownloadUrlByFileGroupKey(@RequestParam("fileGroupKey") String fileGroupKey){
        List<String> urls = null;
        try {
            urls = fileService.getDownloadUrlByFileGroupKey(fileGroupKey);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取文件集合下载地址 失败:"+e.getMessage());
        }
        return urls;
    }

    @GetMapping("/getWxacode")
    public void getWxacode(@RequestParam("fileGroupKey") String fileGroupKey,HttpServletResponse response){
        List<String> ossFileNames = null;
        Map<String,Object> returnMap = null;

        InputStream fis = null;
        try {
            ossFileNames = fileService.getOssFileNames(fileGroupKey);
            String ossFileName = ossFileNames.get(0);
            System.out.println("ossFileName>>>>>>>>>"+ossFileName);

            Map mapParam = new HashMap<>();
            mapParam.put("ossFileName",ossFileName);
            returnMap = fileService.singleDownLoadFileByOssFileName(mapParam);
            fis = (InputStream) returnMap.get("stream");
            response.setHeader("Content-Disposition", "inline;filename="+ returnMap.get("fileName"));
            response.setContentType(returnMap.get("fileType").toString());//也可支持gif
            OutputStream os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("下载文件失败");
        }finally{
            try {
                if(fis!=null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @GetMapping("/singleDownLoadFileByFileUuid")
    public void singleDownLoadFileByFileUuid(@RequestParam("fileUuid") String fileUuid,HttpServletResponse response){
        String ossFileName = null;
        Map<String,Object> returnMap = null;

        InputStream fis = null;
        try {
            ossFileName = fileService.getOssFileNameByFileUuid(fileUuid);
            System.out.println("ossFileName>>>>>>>>>"+ossFileName);

            Map mapParam = new HashMap<>();
            mapParam.put("ossFileName",ossFileName);
            returnMap = fileService.singleDownLoadFileByOssFileName(mapParam);
            fis = (InputStream) returnMap.get("stream");
            response.setHeader("Content-Disposition", "inline;filename="+ returnMap.get("fileName"));
            response.setContentType(returnMap.get("fileType").toString());//也可支持gif
            OutputStream os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("下载文件失败");
        }finally{
            try {
                if(fis!=null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
